package cn.lystudio.rohm_time_op.controller.appApi;

import cn.dev33.satoken.util.SaResult;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.lystudio.rohm_time_op.enums.ApiStatus;
import cn.lystudio.rohm_time_op.exceptions.DownloadAppException;
import cn.lystudio.rohm_time_op.service.AppVersionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/app-api")
@CrossOrigin
@Slf4j
public class AppVersionController {
    @Autowired
    private AppVersionService appVersionService;

    @Value("${appdownload.filepath}")
    private String appdownloadFilePath;

    @GetMapping("/getVersion")
    public SaResult getVersion(@RequestParam(value = "appid",required = true)String appid){
        String version = appVersionService.getVersion(appid);
        if(StrUtil.hasEmpty(version)){
            return SaResult.error("APPID异常");
        } else{
            return SaResult.data(Dict.create().set("version",version));
        }
    }

    @GetMapping("/appdownload")
    public ResponseEntity<InputStreamResource> appdownload(@RequestParam("apkname")String apkname) throws IOException {
        Long startTime=System.currentTimeMillis();  //计算请求时间用
        //读取文件
        FileSystemResource file = new FileSystemResource(new File(appdownloadFilePath.concat(apkname)+".apk"));

        if(!file.exists()){
            //抛自定义异常
            throw new DownloadAppException(ApiStatus.APK_ERROR);
        }
        //设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        //计算用时
        log.debug("download用时:"+(System.currentTimeMillis()-startTime));
        //返回响应
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.contentLength())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(new InputStreamResource(file.getInputStream()));
    }
}
